import { IGameData } from "./IMessage";

export const STORAGE_PREFIX = "HUAIJIU_SANXIAO";
export const GAME_DATA = "GAME_DATA";

export default class StorageUtil {
    private static _instance: StorageUtil = null;

    private storage: string = '';

    public static get instance() {
        if (this._instance === null) {
            this._instance = new this();
        }
        return this._instance;
    }

    private _data: IGameData = null;
    public get data() {
        return this._data;
    }
    public set data(data: IGameData) {
        this._data = data;
    }

    public async get<T extends keyof IGameData>(name: T): Promise<IGameData[T]> {
        this._data = this.read();
        return this._data[name];
    }

    public read(): IGameData {
        this.storage = cc.sys.localStorage.getItem(GAME_DATA);
        this._data = JSON.parse(this.storage);
        if (!this._data) {
            this._data = {
                level: 1,
                progress: { cur: 0, max: 0 },

                cellData: [],
                tempData: [],
                guestData: [],
            }
        }
        return this._data;
    }

    public write(value: IGameData) {
        const storage = JSON.stringify(value);
        if (storage === this.storage) {
            // console.log("数据一致~");
        } else {
            this.storage = storage;
            cc.sys.localStorage.setItem(GAME_DATA, storage);
            // console.log("存数据===>data:", storage);
        }
    }

    public clear() {
        cc.sys.localStorage.clear();
    }

    private getKey() {
        return `${STORAGE_PREFIX}_${GAME_DATA}`;
    }
}